package com.itcast.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 验证码管理
 * @author achen
 * @create 2020-04-19 18:07
 */
@RestController
@RequestMapping("/validate")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    //用户体检预约发送验证码
    @RequestMapping("/sendForOrder")
    public Result sendForOrder(String telephone) {
        //生成验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        System.out.println(code);
        //发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //发送验证码失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

        //验证码发送成功，将验证码缓存到redis中
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER,300,code.toString()); //设置验证码在规定时间内有效，失效后redis自动删除
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //用户登录发送验证码
    @RequestMapping("/sendForLogin")
    public Result sendForLogin(String telephone) {
        //生成验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        System.out.println(code);
        //发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //发送验证码失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

        //验证码发送成功，将验证码缓存到redis中（五分钟后失效）
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN,300,code.toString()); //设置验证码在规定时间内有效，失效后redis自动删除
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

}
